<?php


namespace Xin\Sms;

use Overtrue\EasySms\EasySms;
use Xin\Capsule\Manager;
use Xin\Sms\Contracts\Factory;
use Xin\Support\Arr;

/**
 * @mixin \Xin\Sms\Contracts\Channel
 */
class SmsManager extends Manager implements Factory
{

	/**
	 * 默认的驱动键名
	 */
	public const DEFAULT_DRIVER_KEY = 'channel';

	/**
	 * 驱动的列表键名
	 */
	public const DRIVER_CONFIG_KEY = 'channels';

	/**
	 * @var EasySms
	 */
	protected $easySmsService;

	/**
	 * @param array $config
	 */
	public function __construct(array $config = [])
	{
		$config = array_replace_recursive([
			'defaults' => [
				// EasySms
				// 网关调用策略，默认：顺序调用
				'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

				// 默认可用的发送网关
				'gateways' => [],
			],
		], $config);
		parent::__construct($config);

	}

	/**
	 * @inerhitDoc
	 */
	public function channel($name = null)
	{
		return $this->driver($name);
	}

	/**
	 * 创建EasySms实例
	 * @param string $name
	 * @param array $config
	 * @return HigherOrderEasySmsProxy
	 * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
	 */
	public function createDefaultDriver($name, array $config)
	{
		return new HigherOrderEasySmsProxy(
			$this->easySmsService()->gateway($name), $config
		);
	}

	/**
	 * @inerhitDoc
	 */
	public function getDefaultDriver()
	{
		return $this->getConfig('defaults.channel', 'default');
	}

	/**
	 * @inerhitDoc
	 */
	public function setDefaultDriver($name)
	{
		return $this->getConfig('defaults.channel', 'default');
	}

	/**
	 * @inerhitDoc
	 */
	public function getDriverConfig($name)
	{
		$key = 'channels';

		return $this->getConfig($name ? "{$key}.{$name}" : $key);
	}

	/**
	 * @return EasySms
	 */
	protected function easySmsService()
	{
		if (!$this->easySmsService) {
			$this->easySmsService = new EasySms(
				Arr::transformKeys($this->config, [
					'defaults' => 'default',
					'channels' => 'gateways',
				])
			);
			dd($this->easySmsService);
		}

		return $this->easySmsService;
	}

}
